package com.smg.community.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;


import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@SuppressWarnings("restriction")
public class ImageUtil {
	/**
	 * @author <a href="mailto:lqinglong@yahoo.cn">qinglong.lu</a>
	 * 2008-3-21
	 */
	private String srcpath ;//===源图片路径名称如:c:/1.jpg
	private String subpath ;//===剪切图片存放路径名称.如:c:/2.jpg
	
	private int x;//===剪切点x坐标
	private int y;//===剪切点y坐标
	
	private int cutWidth;//===剪切点宽度
	private int cutHeight;//===剪切点高度
	
	private int width;//按比例缩放的图片宽度
	private int height;//按比例缩放的图片高度
	
	public int getWidth() {
		return width;
	}
	public void setWidth(int width) {
		this.width = width;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int height) {
		this.height = height;
	}
	
	public int getCutWidth() {
		return cutWidth;
	}
	public void setCutWidth(int cutWidth) {
		this.cutWidth = cutWidth;
	}
	public int getCutHeight() {
		return cutHeight;
	}
	public void setCutHeight(int cutHeight) {
		this.cutHeight = cutHeight;
	}
	
	
	
	public ImageUtil(int x,int y,int cutWidth,int cutHeight){
	     this.x = x ;
	     this.y = y ;
	     this.cutWidth = cutWidth;
	     this.cutHeight = cutHeight;
	}
	
	public ImageUtil(int x,int y,int cutWidth,int cutHeight,int width,int height){
	     this.x = x ;
	     this.y = y ;
	     this.cutWidth = cutWidth;
	     this.cutHeight = cutHeight;
	     this.width = width;
	     this.height = height;
	}
	
    public String getSrcpath(){
        return srcpath;
    }
    public void setSrcpath(String srcpath){
        this.srcpath = srcpath;
    }
    public String getSubpath(){
        return subpath;
    }
    public void setSubpath(String subpath){
        this.subpath = subpath;
    }

    public int getX(){
        return x;
    }
    public void setX(int x){
        this.x = x;
    }
    public int getY(){
        return y;
    }
    public void setY(int y){
        this.y = y;
    } 
    /**
     * 对图片裁剪，并把裁剪完成新图片保存
     * @param suffixName 图片后缀名
     */
    public void cut(String suffixName){
    	File uploadFile = new File(subpath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        FileInputStream is = null ;
        ImageInputStream iis =null ;
        try{
            //读取图片文件
            is = new FileInputStream(srcpath);
            /*
             * 返回包含所有当前已注册 ImageReader 的 Iterator，这些 ImageReader
             * 声称能够解码指定格式。 参数：formatName - 包含非正式格式名称 .
             *（例如 "jpeg" 或 "tiff"）等 。 
             */
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName(suffixName);
            ImageReader reader = it.next();
            //获取图片流
            iis = ImageIO.createImageInputStream(is);
            /*
             * <p>iis:读取源.true:只向前搜索 </p>
             * 将它标记为 ‘只向前搜索’。此设置意味着包含在输入源中的图像将只按顺序读取，可能允许 reader
             * 避免缓存包含与以前已经读取的图像关联的数据的那些输入部分。
             */
            reader.setInput(iis,true);
            
            /*
             * <p>描述如何对流进行解码的类<p>.
             * 用于指定如何在输入时从 Java Image I/O 框架的上下文中的流转换一幅图像或一组图像。用于特定图像
             * 格式的插件将从其 ImageReader 实现的 getDefaultReadParam 方法中返回 ImageReadParam 的实例。
             */
            ImageReadParam param = reader.getDefaultReadParam();
            
            
            BufferedImage sourceImg = getImage(srcpath);
            /*
             * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域，通过 Rectangle 对象
             * 的左上顶点的坐标（x，y）、宽度和高度可以定义这个区域。
             * 
             * 首先是在原图切割出需要的部分。切割需要的参数是PointX、PointY、CutWidth、CutHeight，
             * 因为在客户端的程序中是可以缩放原图来进行切割的，所以要在在切割原图时需要先按比例缩放这些参数，
             * 还要注意PointX和CutWidth需要水平方向的比例，PointY和CutHeight需要垂直方向的比例。例如（其中imgPhoto是原图）：
             * 
             * 水平切割点：PointX * imgPhoto.Width / PicWidth；
             * 切割宽度：CutWidth * imgPhoto.Width / PicWidth；
             * 垂直切割点：PointY * imgPhoto.Height / PicHeight；
             * 切割高度：CutHeight * imgPhoto.Height / PicHeight。
             */ 
            Rectangle rect = new Rectangle(x * sourceImg.getWidth() / width, 
            		y * sourceImg.getHeight() / height, 
            		cutWidth * sourceImg.getWidth() / width, 
            		cutHeight * sourceImg.getHeight() / height);
            
            //提供一个 BufferedImage，将其用作解码像素数据的目标
            param.setSourceRegion(rect); 
            
            /*
             * 使用所提供的 ImageReadParam 读取通过索引 imageIndex 指定的对象，并将
             * 它作为一个完整的 BufferedImage 返回。
             */
            BufferedImage bi = reader.read(0,param);
            //保存新图片
            ImageIO.write(bi, suffixName, uploadFile);
            System.out.println("图片裁切完成");
        } catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				if(is != null)is.close();
				if(iis != null)iis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
    }
    
    /**
    * 修改图片大小
    */
    public void alterSize(String srcImgFile,String addChar,int newWidth,int newHeight,String root){
	    //System.out.print("文件路径为:"+"//"+srcImgFile);
	    //String root = session.getServletContext().getRealPath("/");
	    java.io.File file = new java.io.File(root + srcImgFile);
	    if(file.exists()){
	    	System.out.println("文件存在");
	    }else{
	    	System.out.println("文件不存在");
	    }
	    int i = srcImgFile.indexOf(".");
	    int sLen = srcImgFile.length();
	    String suffix = srcImgFile.substring(i, sLen); //带点+后缀名
	    String urlName = srcImgFile.substring(0,i); //路径+文件名
	    String newUrlName = root + urlName + addChar + suffix;
	    //System.out.print("新文件名为"+newUrlName);
	    Image src = null;
	    try{
		    src = javax.imageio.ImageIO.read(file);
		    java.awt.image.BufferedImage tag = new java.awt.image.BufferedImage(newWidth,newHeight,java.awt.image.BufferedImage.TYPE_INT_ARGB);
		    tag.getGraphics().drawImage(src,0,0,newWidth,newHeight,null);
		    FileOutputStream newimage = new FileOutputStream(newUrlName);
		    JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
		    encoder.encode(tag); //近JPEG编码
		    newimage.close();
	    }catch(IOException ee){
		    ee.printStackTrace();
		    System.out.print("这里出错了");
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
    }//End sizeAlter
    
    /** 
     * 把图片印刷到图片上
     *  @param  pressImg -- 水印文件
     *  @param  targetImg  -- 目标文件
     *  @param  x
     *  @param  y
    */ 
    public final static void pressImage(String pressImg, String targetImg) {
    	try{
    		File _file  =   new  File(targetImg);
    		Image src  =  ImageIO.read(_file);
    		int  width  =  src.getWidth( null );
    		int  height  =  src.getHeight( null );
    		BufferedImage image  =   new  BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
    		Graphics g  =  image.createGraphics();
    		g.drawImage(src,  0 ,  0 , width, height,  null );
    		//水印文件 
    		File _filebiao  =   new  File(pressImg);
    		Image src_biao  =  ImageIO.read(_filebiao);
            int  width_biao  =  src_biao.getWidth( null );
            int  height_biao  =  src_biao.getHeight( null );
            g.drawImage(src_biao,width-width_biao,height-height_biao, width_biao,height_biao,  null );
            g.dispose();
            FileOutputStream out  =   new  FileOutputStream(targetImg);
            JPEGImageEncoder encoder  =  JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(image);
            param.setQuality(50f, true);
            encoder.encode(image, param);
            out.close();
    	} catch (Exception e)  {
    		e.printStackTrace();
    	}
    }
    //加水印
    public static boolean createMarkStr(String filePath,String strmark) {
    	ImageIcon imgIcon = new ImageIcon(filePath);
        Image theImg = imgIcon.getImage();
		int offWidth = 250;//水印宽度偏移的位置
        int width = theImg.getWidth(null);
        int height = theImg.getHeight(null);
        BufferedImage bimage = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bimage.createGraphics();
        //设置水印字体
        Font font1 = null;
        if(width>800 || height>600){
        	font1 = new Font("宋体", Font.PLAIN, 18);
			offWidth = 350;
        }else{
        	font1 = new Font("宋体", Font.PLAIN, 12);
        }
        g.setFont(font1);
        g.setColor(Color.WHITE);
        g.drawImage(theImg, 0, 0, null);
        g.drawImage(theImg, width, height, null);
        if(width>140)
        	g.drawString(strmark,width-offWidth, height-8); //添加文字
        else if(width>20)
        	g.drawString("DDCLUB.GSUO.COM",5, height-15); //添加文字
        g.dispose();
        try {
        	FileOutputStream out = new FileOutputStream(filePath);
        	JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        	JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
        	param.setQuality(50f, true);
        	encoder.encode(bimage, param);
        	out.close();
        }
        catch (Exception e) {
        	return false;
        }
        return true;
    }
    /**
     * 根据图片路径获取图片
     * */
    public static BufferedImage getImage(String imgUrl){
    	File file = new File(imgUrl);
        FileInputStream is = null;
        try{
            is = new FileInputStream(file);
        }catch (FileNotFoundException e2){
            e2.printStackTrace();
            //return rect;
        }
        BufferedImage sourceImg = null;
        try{
            sourceImg = javax.imageio.ImageIO.read(is);
        }catch (IOException e1){
            e1.printStackTrace();
            //return rect;
        }
        //System.out.println("width = "+sourceImg.getWidth() + "height = " + sourceImg.getHeight());
        return sourceImg;
    }
    public static void main(String[] args)throws Exception{
        String fileName = "C:\\Users\\xiaomage\\Desktop\\head\\02.gif";
        //String fileName = "D:\\Workspaces\\eclipse 3.7\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp4\\wtpwebapps\\ddmap-web-user\\UserHead\\20111207151332250.jpg";
        ImageUtil iu = new ImageUtil(0,0,93,93);
        iu.setSrcpath(fileName);
        //iu.setSubpath("C:\\Users\\xiaomage\\Desktop\\设置页面929\\images\\M1/201110271441.png");
        iu.setSubpath("D:\\Workspaces\\eclipse 3.7\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp4\\wtpwebapps\\ddmap-web-user\\UploadUserHead\\02.gif");
        iu.cut("gif");   
    }
}
